<template>
    <div class="body-container" @touchstart="onTouchStart" @touchend="onTouchEnd" @touchmove="onTouchMove">
        <report-header title="测试" ref="Box1">
            <template slot="setting">
                <!-- <span >下次刷新:05:00</span> -->
                <!-- <refresh-time style="margin-right:8px;" :refresh_cb="onChangeData"></refresh-time> -->
                <time-count ref="timeCountRef"></time-count>
                <refresh @click="onChangeData" style="margin-right:8px;" theme="filled" size="20" fill="#fff"/>
                <i style="margin-right:10px;font-size: 20px;" class="el-icon-setting" @click="onSettingFiled"></i>
                <expand-up @click="onChangeOpenStatus" v-if="isOpen" theme="outline" size="22" fill="#fff"/>
                <expand-down @click="onChangeOpenStatus" v-if="!isOpen" theme="outline" size="22" fill="#fff"/>
            </template>
        </report-header>
        <!-- 筛选 -->
        <flod-container ref="Box2"  :isOpen="isOpen">
            <template slot="content">
                <body-filter ref="Box2">
                    <filter-item>
                        <el-date-picker v-model="dateRange" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" style="width: 198px;" @change="onChangeDateRange" 
                        :picker-options="{
                            disabledDate(time) {
                                return time.getTime() > Date.now() ;
                            }
                        }">
                        </el-date-picker>
                    </filter-item>
                    <filter-item>
                        <el-select style="width: 142px"  multiple clearable placeholder="请选择所属产品" v-model="product_ids" @change="changeProduct">
                            <el-option
                                v-for="oitme in product_infos"
                                :key="oitme.id"
                                :label="oitme.label"
                                :value="oitme.value"> 
                            </el-option>
                        </el-select>
                    </filter-item>
                    <filter-item>
                        <el-input placeholder="输入广告账户/广告组/广告名称搜索" style="width: 198px;" @change="onChangeData"></el-input>
                    </filter-item>
                    <filter-item>
                        <el-select style="width: 142px" clearable placeholder="请选择广告状态" v-model="filterObj.ads_status" @change="onChangeData" >
                            <el-option
                                v-for="oitme in adsStatus"
                                :key="oitme.value"
                                :label="oitme.label"
                                :value="oitme.value"> 
                            </el-option>
                        </el-select>
                    </filter-item>
                    <filter-item>
                        <filter-gt-lt @change="onChangeValue"></filter-gt-lt>
                    </filter-item>
                    <filter-item>
                        <el-select style="width: 198px" clearable placeholder="请选择用户" v-model="filterObj.uid" @change="onChangeData" >
                            <el-option
                                v-for="oitme in users"
                                :key="oitme.id"
                                :label="oitme.name"
                                :value="oitme.id"> 
                            </el-option>
                        </el-select>
                    </filter-item>
                    <filter-item>
                        <el-select style="width: 142px" clearable placeholder="展示维度" v-model="filterObj.show_type"  @change="onChangeData" >
                                <el-option
                                    v-for="oitme in SHOW_DIMENSION"
                                    :key="oitme.value"
                                    :label="oitme.label"
                                    :value="oitme.value"> 
                                </el-option>
                            </el-select>
                    </filter-item>
                    <filter-item>
                        <label style="font-size:12px;color:#333;margin-right:4px;">是否显示详情</label>
                        <el-switch
                                @change="onChangeDetail"
                                v-model="isShowDetail"
                                active-color="#13ce66"
                                inactive-color="#ff4949">
                            </el-switch> 
                    </filter-item>
                </body-filter>
            </template>
        </flod-container>
        <!-- 筛选end -->
         <!-- 内容区 -->
         <el-card class="box-card"  >
            <no-data v-if="!tableData.length"></no-data>
            <template v-if="tableData.length">
                <ad-report-table :tableHeight="tableHeight" :columns="tableColumns" :data="tableData"></ad-report-table>
                <el-pagination
                style="margin-top: 15px;"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="+page_info.page"
                :page-sizes="[10, 20, 50, 100, 200, 300, 400]"
                :page-size="+page_info.page_size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page_info.total">
                </el-pagination>
            </template>
        </el-card>
        <!-- 内容区end -->

        <!-- 字段设置 -->
        <filed-setting ref="FiledSettingRef" :data="tableColumns" @change="onChangeFiledSetting"></filed-setting>
        <!-- 字段设置 end -->
    </div>
</template>

<script>
import {get_ads_daily_reports} from "@/api/reportData"
import {get_users} from "@/api/login"
import {deepClone, getOffsetUtcDate, getLocalStorage, setLocalStorage, clearLocalData} from "@/utils/public"
import Tools from "../../../utils/tools"
import AdReportTable from './components/adReportTable.vue'
import {TABLE_CLOUMS, DEFAULT_COLUMS, VERSION,SHOW_DIMENSION} from "./config";
import {ExpandDown, ExpandUp, Refresh} from "@icon-park/vue"
import TimeCount from "@/components/uiCommon/TimeCount.vue";
import { setToken } from "@/utils/auth";

export default {
    components: { AdReportTable,ExpandDown, ExpandUp, Refresh, TimeCount },
    name: 'AdReportForms',
    data() {
        return {
            SHOW_DIMENSION,
            fix: 'ad_report_forms_', //cookie前缀
            dateRange: [],
            filterObj: {
                begin_time: '',
                end_time: '',
                product_id: '', // 所属产品
                ads_status: '', // 广告状态
                uid: '', //投手
                show_type: 'product_id',
                is_show_list: 1,
            },
            product_ids: [], //产品ID多选
            // PAUSED 暂停 ACTIVE 投放中
            adsStatus: [
                {value: 'PAUSED', label: "暂停"},
                {value: 'ACTIVE', label: "开启"},
                {value: 'deleted', label: "已删除"},
                {value: 'refusal', label: "已拒审"},
            ],
            product_infos: [],
            otherGtVal: '',
            page_info: {
                page: 1,
                page_size: 20,
                total: 0
            },
            tableColumns: [],
            tableData: [],
            tableHeight: 500,
            touche: null,
            isTouched: false,
            isOpen: true,
            users: [],
            isShowDetail: true,

        }
    },
    created() {
        this.initPage()
    },
    mounted() {
        setTimeout(() => {
            this.changeTableHeight();
        }, 100)

        window.addEventListener("resize", () => {
            // console.log('this.changeTableHeight();')
            this.changeTableHeight();
        })

        // let elTableEl = document.querySelector(".el-table--scrollable-y .el-table__body-wrapper");
        // console.log('.el-table--scrollable-y .el-table__body-wrapper',elTableEl)
    },
    methods: {
        initPage() {
            let versionStr = getLocalStorage('version');
            if(versionStr) {
                if(versionStr != VERSION) {
                    Tools.removeCookie(`${this.fix}columns`)
                    setLocalStorage('version', VERSION)
                }
            }else{
                Tools.removeCookie(`${this.fix}columns`)
                setLocalStorage('version', VERSION)
            }

            this.handleCloums();
            let dateRange = getOffsetUtcDate(new Date(), 0)
            this.dateRange = dateRange;
            [this.filterObj.begin_time, this.filterObj.end_time] = dateRange

            this.on_get_products();
            this.on_get_users();
            this.on_get_ads_daily_reports();
        },
        on_get_users() {
            get_users().then(ret => {
                if(ret && ret.code === 0) {
                    this.users = ret?.list || []
                }
            })
        },
        handleCloums() {
            let tableColumns = deepClone(TABLE_CLOUMS);
            let key = `${this.fix}columns`
            let showCloums = Tools.getCookie(key);
            if(!showCloums) {
                showCloums = deepClone(DEFAULT_COLUMS);
            }
            for(let i = 0; i < showCloums.length; i ++) {
                let vKey = showCloums[i]
                for(let k = 0; k < tableColumns.length; k++) {
                    let item = tableColumns[k];
                    if(item.prop == vKey) {
                        item.checked = true;
                        continue;
                    }
                }
            }

            this.tableColumns = deepClone(tableColumns)
        },
        onChangeValue(info) {
            if(!info) return;
            this.otherGtVal = info;
            this.on_get_ads_daily_reports();
        },
        onChangeDateRange() {
            if(this.dateRange) {
                [this.filterObj.begin_time, this.filterObj.end_time] = this.dateRange
            }else {
                this.filterObj.begin_time = '';
                this.filterObj.end_time = '';
            }
            this.on_get_ads_daily_reports();
        },
        on_get_products() {
            this.$store.dispatch("GET_PRODUCTS").then(list => {
                let newList = [];
                list.forEach(item => {
                    newList.push({value: item.id, label: item.name})
                })

                this.product_infos = deepClone(newList)
            });

        },
        onChangeData() {
            this.on_get_ads_daily_reports();
        },
        changeTableHeight() {
            let box1Height = this.$refs.Box1 && this.$refs.Box1.$el.clientHeight;
            let box2Height = this.$refs.Box2 && this.$refs.Box2.$el.clientHeight;
            let winHeight = document.body.clientHeight || window.innerHeight;
            let tableHeight = winHeight - (box1Height + box2Height + 90) ;
            this.tableHeight = tableHeight < 200 ? 200 : tableHeight;
        },
        transfromPer(objetPer, key) {
            if(objetPer[key] != undefined) {
                objetPer[key] = parseInt(objetPer[key] * 100) + '%'
            }
        },
        on_get_ads_daily_reports() {
            let page_info = deepClone(this.page_info);
            delete page_info.total;

            
            let send_data = {
                ...this.filterObj,
                ...page_info
            }
            if(this.otherGtVal && this.otherGtVal.value) {
                send_data[this.otherGtVal.key] = this.otherGtVal.value;
            }
            this.tableData = []
            Tools.showLoading();
                   
            get_ads_daily_reports(send_data).then(ret => {
                console.log(ret)
                if(ret && ret.code === 0) {
                    let count_data = ret.count_data;
                    let count_product = ret.count_product;
                    let list = []

                    if(count_product) {
                        count_data.cday = '合计';
                        count_data.account_name =  '-----'
                        count_data.adset_name = '-----'
                        count_data.ad_name = '-----'
                        count_data.ads_status = '-----'
                        count_data.product_name = '-----'
                        
                        this.transfromPer(count_data, 'percent_conversions')
                        this.transfromPer(count_data, 'ctr')
                        this.page_info.page = ret.page_info.page || 1;
                        this.page_info.total = ret.page_info.total_number;
                        list.push(count_data);

                        for(let key in count_product) {
                            let item_list = count_product[key].list;
                            delete count_product[key].list;
                            count_product[key]['product_name'] =  count_product[key]['product_name'] + '-小计'
                            count_product[key].account_name = count_product[key]?.account_name || '-----'
                            count_product[key].adset_name = '-----'
                            count_product[key].ad_name = '-----'
                            count_product[key].ads_status = '-----'
                            count_product[key]['stype'] = 1;

                            this.transfromPer(count_product[key], 'percent_conversions')
                            this.transfromPer(count_product[key], 'ctr')

                            item_list.forEach(item => {
                                this.transfromPer(item, 'percent_conversions')
                                this.transfromPer(item, 'ctr')
                                item.isOpenAd = (item.ads_status == 'ACTIVE');
                            });
                            list.push(count_product[key]);
                            list = [...list, ...item_list];
                        }
                    }

                    this.tableData = list;
                   this.onChangeStypeBg()
                }else if(ret&& ret.code === -1001) {
                    this.$message.warning("登录失效请重新登陆！")
                    clearLocalData('token')
                    clearLocalData('user');
                    setToken("")
                    this.$store.commit('SET_TOKEN', '');
                    this.$router.push({
                        name: "login"
                    })
                }
                Tools.hideLoading();
                this.$refs.timeCountRef && this.$refs.timeCountRef.clearSpeed();
            })
        },
        handleSizeChange(val) {
            this.page_info.page = 1;
            this.page_info.page_size = val;
            console.log(`每页 ${val} 条`);
            this.on_get_ads_daily_reports();
        },
        handleCurrentChange(val) {
            this.page_info.page = val;
            this.on_get_ads_daily_reports();
            console.log(`当前页: ${val}`);
        },
        onChangeFlod(info) {
            let {type} = info;
            if(type == 'open') {
                setTimeout(() => {
                    this.changeTableHeight();
                }, 100)
            }
        },
        onSettingFiled() {
            this.$refs.FiledSettingRef && this.$refs.FiledSettingRef.onShow();
        },
        onChangeFiledSetting(info) {
            
            let {cloums, showCloums} = info;

            if(!showCloums.length) {
                showCloums = deepClone(DEFAULT_COLUMS);
                for(let i = 0 ; i < showCloums.length; i ++) {
                    for(let j = 0; j < cloums.length; j ++) {
                        if(cloums[j].prop == showCloums[i]) {
                            cloums[j].checked = true;
                            continue;
                        }
                    }
                }
            }   

            this.tableColumns = deepClone(cloums)

            let name = `${this.fix}columns`
            Tools.setCookie(name, showCloums)
        },
        onTouchStart(e) {
            this.isTouched = true;
            let touches = e.touches[0];
            this.touche = touches;

        },
        onTouchMove(e) {
            if(!this.isTouched) return;
            let touches = e.touches[0];
            let xOffset = Math.abs(touches.pageX - this.touche.pageX);
            let yOffset = Math.abs(touches.pageY - this.touche.pageY);

            setTimeout(() => {
                this.isTouched = false;
                if(xOffset > yOffset) {
                    console.log('横向移动')
                }else {
                    console.log('纵向移动')
                }
            }, 300)
            

        },
        onTouchEnd() {
            this.isTouched = false;
            this.touche = null;
        },
        onChangeOpenStatus() {
            this.isOpen = !this.isOpen;
            this.onChangeFlod({type:'open'})
        },
        onChangeStypeBg() {
            // 改变小计背景颜色
            setTimeout(() => {
                let stypes =  document.getElementsByClassName('stype')
                for(let i = 0; i < stypes.length; i ++) {
                    let sitem = stypes[i];
                    let sitemParent = sitem.parentNode.parentNode;
                    if(sitemParent) {
                        sitemParent.setAttribute('style', 'background:#dbc9c9;')
                    }
                }
            }, 100)
        },
        changeProduct() {
            // console.log(this.product_ids)
            this.filterObj.product_id = this.product_ids.join(',');
            this.onChangeData()
        },
        onChangeDetail() {
            let is_show_list = this.isShowDetail ? 1 : 0;
            this.filterObj.is_show_list = is_show_list;
            this.onChangeData();
        }
    
    }
}
</script>

<style lang="scss" scoped>
::v-deep .el-date-editor .el-range-separator{
    padding: 0 2px;
}
::v-deep .el-table th.el-table__cell>.cell, .el-table .cell{
    padding: 0;
    // white-space: nowrap;
    line-height: 16px;
}
::v-deep .el-table .cell{
    line-height: 16px;
    padding: 0;
}
</style>